﻿using System;
using System.Reflection;
using Common;
using Common.ConfigModel;
using Common.DataModels;
using Microsoft.Extensions.DependencyInjection;

namespace Extensions.Services
{
    public static class AddMediatR
    {
        public static IServiceCollection AddMediatRSetup(this IServiceCollection service, SetupTypesConfig config)
        {
            ArgumentNullException.ThrowIfNull(service);
            if (config.MediatRAssembly!=null)
            {
                service.AddMediatR(p=>p.RegisterServicesFromAssembly(config.MediatRAssembly));
            }
            return service;
        }
        /// <summary>
        /// 手动获取Assembly
        /// </summary>
        /// <param name="service"></param>
        /// <param name="mediatRAssembly"></param>
        /// <returns></returns>
        public static IServiceCollection AddMediatRSetup(this IServiceCollection service, Assembly mediatRAssembly)
        {
            ArgumentNullException.ThrowIfNull(service);
            ArgumentNullException.ThrowIfNull(mediatRAssembly);
            service.AddMediatR(p=>p.RegisterServicesFromAssembly(mediatRAssembly));
            return service;
        }
        /// <summary>
        /// 通过配置文件获取Assembly
        /// </summary>
        /// <param name="service"></param>
        /// <param name="mediatRAssembly"></param>
        /// <returns></returns>
        public static IServiceCollection AddMediatRSetup(this IServiceCollection service)
        {
            ArgumentNullException.ThrowIfNull(service);
            var config = Appsettings.app<Startup>("Startup");
            if (config==null || string.IsNullOrWhiteSpace(config.MediatR))
            {
                throw new Exception("mediatr 的配置有误  请检查配置文件");
            }
            service.AddMediatR(p=>p.RegisterServicesFromAssemblies(Assembly.Load(config.MediatR),Assembly.Load("Extensions")));
            return service;
        }
    }
}
